//
//  EGOPhotoController.m
//  EGOPhotoViewer
//
//  Created by Devin Doty on 1/8/10.
//  Copyright 2010 enormego. All rights reserved.
//
//  Permission is hereby granted, free of charge, to any person obtaining a copy
//  of this software and associated documentation files (the "Software"), to deal
//  in the Software without restriction, including without limitation the rights
//  to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//  copies of the Software, and to permit persons to whom the Software is
//  furnished to do so, subject to the following conditions:
//
//  The above copyright notice and this permission notice shall be included in
//  all copies or substantial portions of the Software.
//
//  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//  IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//  FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//  AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//  LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//  OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//  THE SOFTWARE.
//

#import "EGOPhotoViewController.h"
#import "ImagesScrollViewController.h"
#import "ASIHTTPRequest.h"
#import "CJSONDeserializer.h"
#import "MainViewController.h"
#import "AppDelegate.h"
#import "MyPhoto.h"
#import "UIShareLittleViewController.h"
#import "SendEmailView.h"
#define InfoButtonTag 0x11
#define InfoButtonTag1 0x12


@interface EGOPhotoViewController (Private)
- (void)loadScrollViewWithPage:(NSInteger)page;
- (void)layoutScrollViewSubviews;
- (void)setupScrollViewContentSize;
- (void)enqueuePhotoViewAtIndex:(NSInteger)theIndex;
- (void)setBarsHidden:(BOOL)hidden animated:(BOOL)animated;
- (void)setStatusBarHidden:(BOOL)hidden animated:(BOOL)animated;
- (NSInteger)centerPhotoIndex;
- (void)setupToolbar;
- (void)setViewState;
- (void)setupViewForPopover;
- (void)autosizePopoverToImageSize:(CGSize)imageSize photoImageView:(EGOPhotoImageView*)photoImageView;
@end


@implementation EGOPhotoViewController

@synthesize scrollView=_scrollView;
@synthesize photoSource=_photoSource; 
@synthesize photoViews=_photoViews;
@synthesize _fromPopover;
@synthesize smallphotoSource;
@synthesize m_AssignISVC;
@synthesize m_IsMagezin;
@synthesize m_SrcData;
@synthesize m_NowIndex;
@synthesize m_PageShowIndex;
@synthesize UIShareLittle;

- (id)initWithPhoto:(id<EGOPhoto>)aPhoto {
//	return [self initWithPhotoSource:[[[EGOQuickPhotoSource alloc] initWithPhotos:[NSArray arrayWithObjects:aPhoto,nil]] autorelease]];
    return nil;
}

- (id)initWithImage:(UIImage*)anImage {
	return [self initWithPhoto:[[[EGOQuickPhoto alloc] initWithImage:anImage] autorelease]];
}

- (id)initWithImageURL:(NSURL*)anImageURL {
	return [self initWithPhoto:[[[EGOQuickPhoto alloc] initWithImageURL:anImageURL] autorelease]];
}

- (id)initWithPhotoSource:(id <EGOPhotoSource> )aSource aPhotoSourcesmall:(id <EGOPhotoSource> )aSmallSource{
	if (self = [super init]) {
		
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(toggleBarsNotification:) name:@"EGOPhotoViewToggleBars" object:nil];
		[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(photoViewDidFinishLoading:) name:@"EGOPhotoDidFinishLoading" object:nil];
		
		self.hidesBottomBarWhenPushed = YES;
		self.wantsFullScreenLayout = YES;		
		_photoSource = [aSource retain];
		_pageIndex=0;
        
        smallphotoSource = [aSmallSource retain];
	}
	
	return self;
}

- (id)initWithPopoverController:(id)aPopoverController photoSource:(id <EGOPhotoSource>)aPhotoSource {
//	if (self = [self initWithPhotoSource:aPhotoSource]) {
//		_popover = aPopoverController;
//	}
	
	return nil;
}


#pragma mark -
#pragma mark View Controller Methods

- (void)viewDidLoad {
    [super viewDidLoad];
	
	self.view.backgroundColor = [UIColor blackColor];
	self.wantsFullScreenLayout = YES;
	
	if (!_scrollView) {
		
		_scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
		_scrollView.delegate=self;
		_scrollView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
		_scrollView.multipleTouchEnabled=YES;
		_scrollView.scrollEnabled=YES;
		_scrollView.directionalLockEnabled=YES;
		_scrollView.canCancelContentTouches=YES;
		_scrollView.delaysContentTouches=YES;
		_scrollView.clipsToBounds=YES;
		_scrollView.alwaysBounceHorizontal=YES;
		_scrollView.bounces=YES;
		_scrollView.pagingEnabled=YES;
		_scrollView.showsVerticalScrollIndicator=NO;
		_scrollView.showsHorizontalScrollIndicator=NO;
		_scrollView.backgroundColor = self.view.backgroundColor;
		[self.view addSubview:_scrollView];
	}
	
	if (!_captionView) {
		EGOPhotoCaptionView *view = [[EGOPhotoCaptionView alloc] initWithFrame:CGRectMake(0.0f, self.view.frame.size.height, self.view.frame.size.width, 1.0f)];
		[self.view addSubview:view];
		_captionView=view;
		[view release];
	}
	
	//  load photoviews lazily
	NSMutableArray *views = [[NSMutableArray alloc] init];
	for (unsigned i = 0; i < [self.photoSource numberOfPhotos]; i++) {
		[views addObject:[NSNull null]];
	}
	self.photoViews = views;
	[views release];


#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
	if ([self.photoSource numberOfPhotos] == 1 && UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) {
		
		[self.navigationController setNavigationBarHidden:YES animated:NO];
		//[self.navigationController setToolbarHidden:YES animated:NO];
		
		[self enqueuePhotoViewAtIndex:_pageIndex];
		[self loadScrollViewWithPage:_pageIndex];
		[self setViewState];
		
	}
#endif
	p_TipWordsView = [[UIView alloc] initWithFrame:CGRectMake(30-160, 380, 520, 280)];
    p_TipWordsView.layer.cornerRadius =6.f;
    p_TipWordsView.layer.masksToBounds =YES;
    [p_TipWordsView setBackgroundColor:[UIColor blackColor]];
    p_TipWordsView.alpha = 0.0f;
    p_TipTitleLabel = [[UILabel alloc] initWithFrame:CGRectMake(18-130, 380+12, 484, 32)];
    [p_TipTitleLabel setFont:[UIFont systemFontOfSize:28.f]];
    [p_TipTitleLabel setTextColor:[UIColor whiteColor]];
    [p_TipTitleLabel setBackgroundColor:[UIColor clearColor]];
    p_TipTitleLabel.alpha = 0.f;
    
    
    p_TipContentLabel = [[UITextView alloc] initWithFrame:CGRectMake(18-130,380+52, 484, 214)];
    [p_TipContentLabel setFont:[UIFont systemFontOfSize:18.f]];
    [p_TipContentLabel setBackgroundColor:[UIColor clearColor]];
    p_TipContentLabel.userInteractionEnabled = NO;
    [p_TipContentLabel setTextColor:[UIColor whiteColor]];
    p_TipContentLabel.alpha =0.f;
    
    
    p_SeeForPages = [[UIView alloc] initWithFrame:CGRectMake(30-160, 680, 520, 48)];
    p_SeeForPages.layer.cornerRadius =6.f;
    p_SeeForPages.layer.masksToBounds =YES;
    [p_SeeForPages setBackgroundColor:[UIColor blackColor]];
    p_SeeForPages.alpha = 0.0f;
    p_SeeSmallPageButton = [UIButton buttonWithType:UIButtonTypeCustom];
    p_SeeSmallPageButton.frame =CGRectMake(16-130, 12+680, 25, 25);
    [p_SeeSmallPageButton setImage:[UIImage imageNamed:@"pagebutton.png"] forState:UIControlStateNormal];
    [p_SeeSmallPageButton addTarget:self action:@selector(showSmallPageControl) forControlEvents:UIControlEventTouchUpInside];
    [p_SeeSmallPageButton retain];
    p_SeeSmallPageButton.alpha =0.f;
    
    p_LabelButtonTip = [[UILabel alloc] initWithFrame:CGRectMake(52-130, 12+680, 52, 26)];
    [p_LabelButtonTip setBackgroundColor:[UIColor clearColor]];
    [p_LabelButtonTip setTextColor:[UIColor whiteColor]];
    p_LabelButtonTip.alpha =0.0;
    p_LabelButtonTip.text =@"预览";
    [p_LabelButtonTip setFont:[UIFont systemFontOfSize:24]];
    
    [self.view addSubview:p_TipWordsView];
    [self.view addSubview:p_SeeForPages];
    
    [self.view addSubview:p_TipTitleLabel];
    [self.view addSubview:p_TipContentLabel];
    [self.view addSubview:p_SeeSmallPageButton];
    [self.view addSubview:p_LabelButtonTip];
    
    //240,440
    p_ContextController = [[UIView alloc] initWithFrame:CGRectMake(30, 634, 520, 0)];
    [p_ContextController setBackgroundColor:[UIColor blackColor]];
    p_ContextController.clipsToBounds =YES;
    
    UIScrollView* tScrollIn = [[UIScrollView alloc] initWithFrame:CGRectMake(20, 45, 480, 130)];
    [tScrollIn setBackgroundColor:[UIColor blackColor]];
    tScrollIn.pagingEnabled =YES;
    
    UIPageControl* pageControl = [[UIPageControl alloc] initWithFrame:CGRectMake(15, 204, 480, 20)];
    pageControl.numberOfPages = smallphotoSource.numberOfPhotos%3 == 0 ? smallphotoSource.numberOfPhotos/3 : smallphotoSource.numberOfPhotos/3+1;
    pageControl.currentPage = 0;
    [p_ContextController addSubview:pageControl];
    [pageControl release];
    
    tScrollIn.contentSize =CGSizeMake(480*pageControl.numberOfPages, 130);
    tScrollIn.showsHorizontalScrollIndicator =NO;
    for (int i=0; i<pageControl.numberOfPages; i++) {
        UIView* tInView =[[UIView alloc] initWithFrame:CGRectMake(480*i, 0, 480, 190)];
        [tInView setBackgroundColor:[UIColor clearColor]];
        for (int j=i*3; j<(i+1)*3; j++) {
            if (j >= smallphotoSource.numberOfPhotos) {
                break;
            }
            UIButton* tViewButton = [UIButton buttonWithType:UIButtonTypeCustom];
            tViewButton.tag =j;
            [tViewButton addTarget:self action:@selector(jumpToIndex:) forControlEvents:UIControlEventTouchUpInside];
            tViewButton.highlighted =YES;
            id<EGOPhoto> object = [self.smallphotoSource photoAtIndex:j];
            tViewButton.frame =CGRectMake(((j%3)*170), 0, 150, 130);
            [tViewButton setImage:object.image forState:UIControlStateNormal];
            
            [tViewButton setBackgroundColor:[UIColor grayColor]];
            [tInView addSubview:tViewButton];
        }
        [tScrollIn addSubview:tInView];
        [tInView release];
    }
    
    [p_ContextController addSubview:tScrollIn];
    [tScrollIn release];
    
    [self.view addSubview:p_ContextController];
}
-(void)showControl:(UIButton*)ib
{
    if (ib.tag == 1000) {
        [p_PopShowWord dismissPopoverAnimated:NO];
        if (p_SendMailView == nil) {
            p_SendMailView = [[SendEmailView alloc] init];
            [p_SendMailView.view setBackgroundColor:[UIColor whiteColor]];
            UIView* tBackView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
            [tBackView setBackgroundColor:[UIColor blackColor]];
            tBackView.alpha = 0.5;
            p_SendMailView.m_CountBackGroundView = tBackView;
            [tBackView release];
        }
        EGOPhotoImageView * photoView = [self.photoViews objectAtIndex:_pageIndex];
        UIImage* image =photoView.imageView.image;
        p_SendMailView.m_EmailImage = image;
        p_SendMailView.view.frame = CGRectMake(150, ScreenHeight, ScreenWidth-300, ScreenHeight);
        [self.navigationController.view addSubview:p_SendMailView.m_CountBackGroundView];
        [self.navigationController.view addSubview:p_SendMailView.view];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.2];
        p_SendMailView.view.frame = CGRectMake(150, 0, ScreenWidth-300, ScreenHeight);
        [UIView commitAnimations];
    }
    else if(ib.tag == 1001)
    {
        if (UIShareLittle == nil) {
                 UIShareLittle = [[UIShareLittleViewController alloc] init];
        }
        EGOPhotoImageView * photoView = [self.photoViews objectAtIndex:_pageIndex];
        UIImage* image =photoView.imageView.image;
        UIShareLittle.m_SendImg = image;
        UIShareLittle.view.frame = CGRectMake(0, ScreenHeight, ScreenWidth, ScreenHeight);
        [self.navigationController.view addSubview:UIShareLittle.view];
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
        [UIView setAnimationDuration:0.2];
        UIShareLittle.view.frame = CGRectMake(0, 0, ScreenWidth, ScreenHeight);
        [UIView commitAnimations];
    }
    else if(ib.tag == 1002)
    {
        EGOPhotoImageView * photoView = [self.photoViews objectAtIndex:_pageIndex];
        UIImage* image =photoView.imageView.image;
        if (image != nil) {
            NSLog(@"single click %@",image);
            UIImageWriteToSavedPhotosAlbum(image, self, @selector(image:didFinishSavingWithError: contextInfo:), nil);
            
        }else
        {
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照片失败"
                                  
                                                            message:@"图片还没的下载完成"
                                  
                                                           delegate:self
                                  
                                                  cancelButtonTitle:@"OK"
                                  
                                                  otherButtonTitles:nil];
            
            [alert show];
            
            [alert release];
        }
    }
    [p_PopShowWord dismissPopoverAnimated:YES];
}
- (void) image: (UIImage *) image didFinishSavingWithError: (NSError *) error
   contextInfo: (void *) contextInfo{
    if (error == nil) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照片成功"
                              
                                                        message:@"图片已正确的储存至照片数据"
                              
                                                       delegate:self
                              
                                              cancelButtonTitle:@"OK"
                              
                                              otherButtonTitles:nil];
        
        [alert show];
        
        [alert release];
    }else{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"存储照片失败"
                              
                                                        message:@"图片保存失败请重试！"
                              
                                                       delegate:self
                              
                                              cancelButtonTitle:@"OK"
                              
                                              otherButtonTitles:nil];
        
        [alert show];
        
        [alert release];
    }
}
-(void) showSmallPageControl{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.3];
    if (p_ContextController.frame.origin.y == 482) {
        p_TipTitleLabel.frame = CGRectMake(48, 152+240, 484, 32);
        p_TipContentLabel.frame = CGRectMake(48,192+240, 484, 214);
        p_LabelButtonTip.frame = CGRectMake(82, 452+240, 52, 26);
        p_SeeSmallPageButton.frame =CGRectMake(46, 452+240, 25, 25);
        
        p_SeeForPages.frame = CGRectMake(30, 440+240, 520, 48);
        p_TipWordsView.frame = CGRectMake(30, 140+240, 520, 280);
        p_ContextController.frame =CGRectMake(30, 482+240, 520, 0);
    }else{
        p_TipTitleLabel.frame = CGRectMake(48, 152, 484, 32);
        p_TipContentLabel.frame = CGRectMake(48,192, 484, 214);
        p_LabelButtonTip.frame = CGRectMake(82, 452, 52, 26);
        p_SeeSmallPageButton.frame =CGRectMake(46, 452, 25, 25);
        
        p_SeeForPages.frame = CGRectMake(30, 440, 520, 48);
        p_TipWordsView.frame = CGRectMake(30, 140, 520, 280);
        p_ContextController.frame =CGRectMake(30, 482, 520, 240);
    }
    [UIView commitAnimations];
}

-(void) jumpToIndex:(UIButton*)sender{
    [self moveToPhotoAtIndex:sender.tag animated:NO];
}

- (void)viewWillAppear:(BOOL)animated{
	[super viewWillAppear:animated];
	
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		
		UIView *view = self.view;
		if (self.navigationController) {
			view = self.navigationController.view;
		}
		
		while (view != nil) {
			
			if ([view isKindOfClass:NSClassFromString(@"UIPopoverView")]) {
				
				_popover = view;
				break;
			
			} 
			view = view.superview;
		}
		
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
		if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad && _popover==nil) {
			[self.navigationController setNavigationBarHidden:NO animated:NO];
            self.navigationController.navigationBar.alpha =0.0;
		}
#endif
		
	} else {
		
		_popover = nil;
		
	}
	
	if(!_storedOldStyles) {
		_oldStatusBarSyle = [UIApplication sharedApplication].statusBarStyle;
		
		_oldNavBarTintColor = [self.navigationController.navigationBar.tintColor retain];
		_oldNavBarStyle = self.navigationController.navigationBar.barStyle;
		_oldNavBarTranslucent = self.navigationController.navigationBar.translucent;
		
		_oldToolBarTintColor = [self.navigationController.toolbar.tintColor retain];
		_oldToolBarStyle = self.navigationController.toolbar.barStyle;
		_oldToolBarTranslucent = self.navigationController.toolbar.translucent;
		//_oldToolBarHidden = [self.navigationController isToolbarHidden];
		
		_storedOldStyles = YES;
	}	
	
//	if ([self.navigationController isToolbarHidden] && (!_popover || ([self.photoSource numberOfPhotos] > 1))) {
//		[self.navigationController setToolbarHidden:NO animated:YES];
//	}
	
	if (!_popover) {
		self.navigationController.navigationBar.tintColor = nil;
		self.navigationController.navigationBar.barStyle = UIBarStyleBlack;
		self.navigationController.navigationBar.translucent = YES;
		
		self.navigationController.toolbar.tintColor = nil;
		self.navigationController.toolbar.barStyle = UIBarStyleBlack;
		self.navigationController.toolbar.translucent = YES;
	}

	
	[self setupToolbar];
	[self setupScrollViewContentSize];
	[self moveToPhotoAtIndex:_pageIndex animated:NO];
	
	if (_popover) {
		[self addObserver:self forKeyPath:@"contentSizeForViewInPopover" options:NSKeyValueObservingOptionNew context:NULL];
	}
	
}

- (void)viewWillDisappear:(BOOL)animated{
	[super viewWillDisappear:animated];
	
	self.navigationController.navigationBar.barStyle = _oldNavBarStyle;
	self.navigationController.navigationBar.tintColor = _oldNavBarTintColor;
	self.navigationController.navigationBar.translucent = _oldNavBarTranslucent;
	
	[[UIApplication sharedApplication] setStatusBarStyle:_oldStatusBarSyle animated:YES];
	
    [self.navigationController setNavigationBarHidden:YES];
//	if(!_oldToolBarHidden) {
//		
////		if ([self.navigationController isToolbarHidden]) {
////			[self.navigationController setToolbarHidden:NO animated:YES];
////		}
//		
//		self.navigationController.toolbar.barStyle = _oldNavBarStyle;
//		self.navigationController.toolbar.tintColor = _oldNavBarTintColor;
//		self.navigationController.toolbar.translucent = _oldNavBarTranslucent;
//		
//	} else {
//		
//		//[self.navigationController setToolbarHidden:_oldToolBarHidden animated:YES];
//		
//	}
	
	if (_popover) {
		[self removeObserver:self forKeyPath:@"contentSizeForViewInPopover"];
	}
	
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
	
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
		return YES;
	}
#endif
	
   	return (UIInterfaceOrientationIsLandscape(interfaceOrientation) || interfaceOrientation == UIInterfaceOrientationPortrait);
	
}

- (void)willRotateToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
	_rotating = YES;
	
	if (UIInterfaceOrientationIsLandscape(toInterfaceOrientation) && !_popover) {
		CGRect rect = [[UIScreen mainScreen] bounds];
		self.scrollView.contentSize = CGSizeMake(rect.size.height * [self.photoSource numberOfPhotos], rect.size.width);
	}
	
	//  set side views hidden during rotation animation
	NSInteger count = 0;
	for (EGOPhotoImageView *view in self.photoViews){
		if ([view isKindOfClass:[EGOPhotoImageView class]]) {
			if (count != _pageIndex) {
				[view setHidden:YES];
			}
		}
		count++;
	}
	
}

- (void)willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)toInterfaceOrientation duration:(NSTimeInterval)duration{
	
	for (EGOPhotoImageView *view in self.photoViews){
		if ([view isKindOfClass:[EGOPhotoImageView class]]) {
			[view rotateToOrientation:toInterfaceOrientation];
		}
	}
		
}

- (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation{
	
	[self setupScrollViewContentSize];
	[self moveToPhotoAtIndex:_pageIndex animated:NO];
	[self.scrollView scrollRectToVisible:((EGOPhotoImageView*)[self.photoViews objectAtIndex:_pageIndex]).frame animated:YES];
	
	//  unhide side views
	for (EGOPhotoImageView *view in self.photoViews){
		if ([view isKindOfClass:[EGOPhotoImageView class]]) {
			[view setHidden:NO];
		}
	}
	_rotating = NO;
	
}

//- (void)done:(id)sender {
//	[self dismissModalViewControllerAnimated:YES];
//}

-(void) exitToMainView{
    [self.navigationController popViewControllerAnimated:YES];
}

-(void) showAboutView{
    if (p_PopShowWord == nil) {
        UIViewController* tPopViewController = [[UIViewController alloc] init];
        UITextView* tTextWord = [[UITextView alloc] initWithFrame:CGRectMake(0, 0, 320, 400)];
        [tTextWord setText:@"  万科企业股份有限公司成立于1984年5月，是目前中国最大的专业住宅开发企业。2010年公司完成新开工面积1248万平方米，实现销售面积897.7万平方米，销售金额1081.6亿元。 营业收入507.1亿元，净利润72.8亿元。\r\n  万科认为，坚守价值底线、拒绝利益诱惑，坚持以专业能力从市场获取公平回报，是万科获得成功的基石。公司致力于通过规范、透明的企业文化和稳健、专注的发展模式，成为最受客户、最受投资者、最受员工、最受合作伙伴欢迎，最受社会尊重的企业。凭借公司治理和道德准则上的表现，公司连续八次获得“中国最受尊敬企业”称号。"];
        [tPopViewController.view addSubview:tTextWord];
        [tTextWord setFont:[UIFont systemFontOfSize:18.f]];
        [tTextWord release];
        [tPopViewController.view setBackgroundColor:[UIColor clearColor]];
        p_PopShowWord = [[UIPopoverController alloc] initWithContentViewController:tPopViewController];
        [tPopViewController release];
        p_PopShowWord.popoverContentSize =CGSizeMake(320, 400);
    }
    UIButton* tInfoButton = (UIButton*)[self.navigationController.navigationBar viewWithTag:InfoButtonTag];
    [p_PopShowWord presentPopoverFromRect:CGRectMake(0, -360, 320, 400) inView:tInfoButton permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];
}

-(void) showfunctionView{
    if (p_PopShowWord == nil) {
        UIViewController* tPopViewController = [[UIViewController alloc] init];
        tPopViewController.view.frame = CGRectMake(0, 0, 320, 210);
        [tPopViewController.view setBackgroundColor:[UIColor lightGrayColor]];
        UIButton* ibutton = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        ibutton.frame =CGRectMake(10, 10, 300, 60);
        ibutton.tag = 1000;
        ibutton.titleLabel.font = [UIFont systemFontOfSize:23];
        [ibutton setTitle:@"使用Email分享" forState:UIControlStateNormal];
  //     [ibutton setImage:[UIImage imageNamed:@"pagebutton.png"] forState:UIControlStateNormal];
        [ibutton addTarget:self action:@selector(showControl:) forControlEvents:UIControlEventTouchUpInside];
//        ibutton.alpha =0.f;
        [tPopViewController.view addSubview:ibutton];
        
        UIButton* ibutton1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        ibutton1.frame =CGRectMake(10, 80, 300, 60);
        ibutton1.tag = 1001;
        ibutton1.titleLabel.font = [UIFont systemFontOfSize:23];
        [ibutton1 setTitle:@"分享到新浪微博" forState:UIControlStateNormal];
        //     [ibutton setImage:[UIImage imageNamed:@"pagebutton.png"] forState:UIControlStateNormal];
        [ibutton1 addTarget:self action:@selector(showControl:) forControlEvents:UIControlEventTouchUpInside];
        //        ibutton.alpha =0.f;
        [tPopViewController.view addSubview:ibutton1];
        
        UIButton* ibutton2 = [UIButton buttonWithType:UIButtonTypeRoundedRect];
        ibutton2.frame =CGRectMake(10, 150, 300, 60);
        ibutton2.tag = 1002;
        ibutton2.titleLabel.font = [UIFont systemFontOfSize:23];
        [ibutton2 setTitle:@"保存到相册" forState:UIControlStateNormal];
        //     [ibutton setImage:[UIImage imageNamed:@"pagebutton.png"] forState:UIControlStateNormal];
        [ibutton2 addTarget:self action:@selector(showControl:) forControlEvents:UIControlEventTouchUpInside];
        //        ibutton.alpha =0.f;
        [tPopViewController.view addSubview:ibutton2];
        p_PopShowWord = [[UIPopoverController alloc] initWithContentViewController:tPopViewController];
//        [tPopViewController release];
        p_PopShowWord.popoverContentSize =CGSizeMake(320, 220);
    }

    UIButton* tInfoButton = (UIButton*)[self.navigationController.navigationBar viewWithTag:InfoButtonTag1];
    [p_PopShowWord presentPopoverFromRect:CGRectMake(0, 0,50,40 ) inView:tInfoButton permittedArrowDirections:UIPopoverArrowDirectionUp animated:YES];

}
- (void)setupToolbar {
    UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(exitToMainView)];
    self.navigationController.navigationBar.topItem.hidesBackButton = YES;
    self.navigationItem.leftBarButtonItem =doneButton;
    [doneButton release];
    
    UIButton* tInfoButton = [UIButton buttonWithType:UIButtonTypeCustom];
    tInfoButton.tag = InfoButtonTag;
    [tInfoButton setImage:[UIImage imageNamed:@"aboutbutton.png"] forState:UIControlStateNormal];
    tInfoButton.frame = CGRectMake(960, 0, 50, 40);
    [tInfoButton addTarget:self action:@selector(showAboutView) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:tInfoButton];
    
    UIButton* tInfoButton1  = [UIButton buttonWithType:UIButtonTypeCustom];
    tInfoButton1.tag = InfoButtonTag1;
    [tInfoButton1 setImage:[UIImage imageNamed:@"sendbutton.png"] forState:UIControlStateNormal];
    tInfoButton1.frame = CGRectMake(910, 0, 50, 40);
    [tInfoButton1 addTarget:self action:@selector(showfunctionView) forControlEvents:UIControlEventTouchUpInside];
    [self.navigationController.navigationBar addSubview:tInfoButton1];
    
//	
//	[self setupViewForPopover];
//
//	if(_popover && [self.photoSource numberOfPhotos] == 1) {
//		[self.navigationController setToolbarHidden:YES animated:NO];
//		return;
//	}
//	
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
//	if (!_popover && UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad && !_fromPopover) {
//		if (self.modalPresentationStyle == UIModalPresentationFullScreen) {
//			UIBarButtonItem *doneButton = [[UIBarButtonItem alloc] initWithTitle:@"Done" style:UIBarButtonItemStyleDone target:self action:@selector(done:)];
//			self.navigationItem.rightBarButtonItem = doneButton;
//			[doneButton release];
//		}
//	} else if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPhone) {
//		[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
//	}
//#else 
//	[[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackTranslucent animated:YES];
//#endif
//	
//	UIBarButtonItem *action = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAction target:self action:@selector(actionButtonHit:)];
//	UIBarButtonItem *flex = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:nil action:nil];
//	
//	if ([self.photoSource numberOfPhotos] > 1) {
//		
//		UIBarButtonItem *fixedCenter = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//		fixedCenter.width = 80.0f;
//		UIBarButtonItem *fixedLeft = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
//		fixedLeft.width = 40.0f;
//		
//		if (_popover && [self.photoSource numberOfPhotos] > 1) {
//			UIBarButtonItem *scaleButton = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"egopv_fullscreen_button.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(toggleFullScreen:)];
//			self.navigationItem.rightBarButtonItem = scaleButton;
//			[scaleButton release];
//		}		
//
//		
//		UIBarButtonItem *left = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"egopv_left.png"] style:UIBarButtonItemStylePlain target:self action:@selector(moveBack:)];
//		UIBarButtonItem *right = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"egopv_right.png"] style:UIBarButtonItemStylePlain target:self action:@selector(moveForward:)];
//		
//		[self setToolbarItems:[NSArray arrayWithObjects:fixedLeft, flex, left, fixedCenter, right, flex, action, nil]];
//		
//		_rightButton = right;
//		_leftButton = left;
//		
//		[fixedCenter release];
//		[fixedLeft release];
//		[right release];
//		[left release];
//		
//	} else {
//		[self setToolbarItems:[NSArray arrayWithObjects:flex, action, nil]];
//	}
//	
//	_actionButton=action;
//	
//	[action release];
//	[flex release];
//	
}

- (NSInteger)currentPhotoIndex{
	
	return _pageIndex;
	
}


#pragma mark -
#pragma mark Popver ContentSize Observing

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{	
	[self setupScrollViewContentSize];
	[self layoutScrollViewSubviews];
}


#pragma mark -
#pragma mark Bar/Caption Methods

- (void)setStatusBarHidden:(BOOL)hidden animated:(BOOL)animated{
	if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) return; 
	
	if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 3.2) {
		
		[[UIApplication sharedApplication] setStatusBarHidden:hidden withAnimation:UIStatusBarAnimationFade];
		
	} else {
#if __IPHONE_OS_VERSION_MAX_ALLOWED < 30200
		[[UIApplication sharedApplication] setStatusBarHidden:hidden animated:animated];
#endif
	}

}

- (void)setBarsHidden:(BOOL)hidden animated:(BOOL)animated{
	if (hidden&&_barsHidden) return;
	
	if (_popover && [self.photoSource numberOfPhotos] == 0) {
		[_captionView setCaptionHidden:hidden];
		return;
	}
		
	[self setStatusBarHidden:hidden animated:animated];
	
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
	if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
		
		if (!_popover) {
			if (!hidden) {
                p_ContextController.frame =CGRectMake(30, 482+240, 520, 0);
                
                p_TipWordsView.frame = CGRectMake(30, 380, 520, 280);
                p_TipTitleLabel.frame = CGRectMake(18+30, 380+12, 484, 32);
                p_SeeForPages.frame = CGRectMake(30, 680, 520, 48);
                p_TipContentLabel.frame = CGRectMake(18+30,380+52, 484, 214);
                p_SeeSmallPageButton.frame =CGRectMake(16+30, 12+680, 25, 25);
                p_LabelButtonTip.frame = CGRectMake(52+30, 12+680, 52, 26);
            }
            self.navigationController.navigationBar.hidden =NO;
			if (animated) {
				[UIView beginAnimations:nil context:NULL];
				[UIView setAnimationDuration:0.3f];
				[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
			}
            if (hidden) {
                NSDictionary* tShowDic = [m_AssignISVC.m_ImagesDataArr objectAtIndex:self.currentPhotoIndex];
                NSString* tTitlePath = [tShowDic objectForKey:@"title"];
                NSString* tContentPath = [tShowDic objectForKey:@"digest"];
                if (![tTitlePath isEqualToString:@""] || ![tContentPath isEqualToString:@""]) {
                    p_TipWordsView.frame = CGRectMake(30, 380, 520, 280);
                    p_TipWordsView.alpha =0.6f;
                    p_TipTitleLabel.frame = CGRectMake(18+30, 380+12, 484, 32);
                    p_TipTitleLabel.alpha =1.0f;
                    p_TipTitleLabel.text =tTitlePath;
                    p_TipContentLabel.frame = CGRectMake(18+30,380+52, 484, 214);
                    p_TipContentLabel.alpha =1.0f;
                    p_TipContentLabel.text = tContentPath;
                }

                p_SeeForPages.frame = CGRectMake(30, 680, 520, 48);
                p_SeeForPages.alpha = 0.6f;
                
                p_SeeSmallPageButton.frame =CGRectMake(16+30, 12+680, 25, 25);
                p_SeeSmallPageButton.alpha =1.0f;
                
                p_LabelButtonTip.frame = CGRectMake(52+30, 12+680, 52, 26);
                p_LabelButtonTip.alpha = 1.0f;
            }else{
                p_TipWordsView.frame = CGRectMake(30-160, 380, 520, 280);
                p_TipWordsView.alpha =0.0f;
                p_SeeForPages.frame = CGRectMake(30-160, 680, 520, 48);
                p_SeeForPages.alpha = 0.0f;
                
                p_TipTitleLabel.frame = CGRectMake(18-130, 380+12, 484, 32);
                p_TipTitleLabel.alpha =0.0f;
                p_TipContentLabel.frame = CGRectMake(18-130,380+52, 484, 214);
                p_TipContentLabel.alpha =0.0f;
                p_SeeSmallPageButton.frame =CGRectMake(16-130, 12+680, 25, 25);
                p_SeeSmallPageButton.alpha =0.0f;
                p_LabelButtonTip.frame = CGRectMake(52-130, 12+680, 52, 26);
                p_LabelButtonTip.alpha = 0.0f;
            }

            
			self.navigationController.navigationBar.alpha = hidden ? 0.8f : 0.0f;
			self.navigationController.toolbar.alpha = hidden ? 0.8f : 0.0f;
			
			if (animated) {
				[UIView commitAnimations];
			}
			
		} 
		
	} else {
		
		[self.navigationController setNavigationBarHidden:hidden animated:animated];
		//[self.navigationController setToolbarHidden:hidden animated:animated];
		
	}
#else
	
	[self.navigationController setNavigationBarHidden:hidden animated:animated];
	//[self.navigationController setToolbarHidden:hidden animated:animated];
	
#endif
	
	if (_captionView) {
		[_captionView setCaptionHidden:hidden];
	}
	
	_barsHidden=hidden;
	
}

- (void)toggleBarsNotification:(NSNotification*)notification{
	[self setBarsHidden:!_barsHidden animated:YES];
}


#pragma mark -
#pragma mark FullScreen Methods

- (void)setupViewForPopover{
	
	if (!_popoverOverlay && _popover && [self.photoSource numberOfPhotos] == 1) {
				
		UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0.0f, self.view.frame.size.height, self.view.frame.size.width, 40.0f)];
		view.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin;
		view.backgroundColor = [UIColor colorWithWhite:0.0f alpha:0.2f];
		_popoverOverlay = view;
		[self.view addSubview:view];
		[view release];
		
		UIView *borderView = [[UIView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, _popoverOverlay.frame.size.width, 1.0f)];
		borderView.autoresizingMask = view.autoresizingMask;
		[_popoverOverlay addSubview:borderView];
		[borderView setBackgroundColor:[UIColor colorWithWhite:1.0f alpha:0.4f]];
		[borderView release];
		
		UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
		[button setImage:[UIImage imageNamed:@"egopv_fullscreen_button.png"] forState:UIControlStateNormal];
		button.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin;
		[button addTarget:self action:@selector(toggleFullScreen:) forControlEvents:UIControlEventTouchUpInside];
		button.frame = CGRectMake(view.frame.size.width - 40.0f, 0.0f, 40.0f, 40.0f);
		[view addSubview:button];
		
		[UIView beginAnimations:nil context:NULL];
		[UIView setAnimationDuration:0.3f];
		[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
		view.frame = CGRectMake(0.0f, self.view.bounds.size.height - 40.0f, self.view.bounds.size.width, 40.0f);
		[UIView commitAnimations];
		
	}
	
}

- (CATransform3D)transformForCurrentOrientation{
	
	UIInterfaceOrientation orientation = [[UIApplication sharedApplication] statusBarOrientation];
	
	switch (orientation) {
		case UIInterfaceOrientationPortraitUpsideDown:
			return CATransform3DMakeRotation((M_PI/180)*180, 0.0f, 0.0f, 1.0f);
			break;
		case UIInterfaceOrientationLandscapeRight:
			return CATransform3DMakeRotation((M_PI/180)*90, 0.0f, 0.0f, 1.0f);
			break;
		case UIInterfaceOrientationLandscapeLeft:
			return CATransform3DMakeRotation((M_PI/180)*-90, 0.0f, 0.0f, 1.0f);
			break;
		default:
			return CATransform3DIdentity;
			break;
	}
	
}

- (void)toggleFullScreen:(id)sender{
	
	_fullScreen = !_fullScreen;
	
	if (!_fullScreen) {
		
		NSInteger pageIndex = 0;
		if (self.modalViewController && [self.modalViewController isKindOfClass:[UINavigationController class]]) {
			UIViewController *controller = [((UINavigationController*)self.modalViewController) visibleViewController];
			if ([controller isKindOfClass:[self class]]) {
				pageIndex = [(EGOPhotoViewController*)controller currentPhotoIndex];
			}
		}		
		[self moveToPhotoAtIndex:pageIndex animated:NO];
		[self.navigationController dismissModalViewControllerAnimated:NO];
		
	}
	
	EGOPhotoImageView *_currentView = [self.photoViews objectAtIndex:_pageIndex];
	BOOL enabled = [UIView areAnimationsEnabled];
	[UIView setAnimationsEnabled:NO];
	[_currentView killScrollViewZoom];
	[UIView setAnimationsEnabled:enabled];
	UIImageView *_currentImage = _currentView.imageView;
	
	UIWindow *keyWindow = [[UIApplication sharedApplication] keyWindow];
	UIView *backgroundView = [[UIView alloc] initWithFrame:CGRectZero];
	backgroundView.layer.transform = [self transformForCurrentOrientation];
	[keyWindow addSubview:backgroundView];
	backgroundView.frame = [[UIScreen mainScreen] applicationFrame];
	_transferView = backgroundView;
	[backgroundView release];
	
	CGRect newRect = [self.view convertRect:_currentView.scrollView.frame toView:_transferView];
	UIImageView *_imageView = [[UIImageView alloc] initWithFrame:_fullScreen ? newRect : _transferView.bounds];	
	_imageView.contentMode = UIViewContentModeScaleAspectFit;
	[_imageView setImage:_currentImage.image];
	[_transferView addSubview:_imageView];
	[_imageView release];
	
	self.scrollView.hidden = YES;
	
	CABasicAnimation *animation = [CABasicAnimation animationWithKeyPath:@"backgroundColor"];
	animation.fromValue = _fullScreen ? (id)[UIColor clearColor].CGColor : (id)[UIColor blackColor].CGColor;
	animation.toValue = _fullScreen ? (id)[UIColor blackColor].CGColor : (id)[UIColor clearColor].CGColor;
	animation.removedOnCompletion = NO;
	animation.fillMode = kCAFillModeForwards;
	animation.duration = 0.4f;
	[_transferView.layer addAnimation:animation forKey:@"FadeAnimation"];
	
	[UIView beginAnimations:nil context:NULL];
	[UIView setAnimationDuration:0.4f];
	[UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
	[UIView setAnimationDelegate:self];
	[UIView setAnimationDidStopSelector:@selector(fullScreenAnimationDidStop:finished:context:)];
	_imageView.frame = _fullScreen ? _transferView.bounds : newRect;
	[UIView commitAnimations];
	
}

- (void)fullScreenAnimationDidStop:(NSString *)animationID finished:(NSNumber *)finished context:(void *)context{
	
	if (finished) {
		
		self.scrollView.hidden = NO;
		
		if (_transferView) {
			[_transferView removeFromSuperview];
			_transferView=nil;
		}
		
		if (_fullScreen) {
			
			BOOL enabled = [UIView areAnimationsEnabled];
			[UIView setAnimationsEnabled:NO];
			
			EGOPhotoViewController *controller = [[EGOPhotoViewController alloc] initWithPhotoSource:self.photoSource aPhotoSourcesmall:smallphotoSource];
			controller._fromPopover = YES;
			UINavigationController *navController = [[UINavigationController alloc] initWithRootViewController:controller];
			
			navController.modalPresentationStyle = UIModalPresentationFullScreen;
			[self.navigationController presentModalViewController:navController animated:NO];
			[controller moveToPhotoAtIndex:_pageIndex animated:NO];
			
			[navController release];
			[controller release];
			
			[UIView setAnimationsEnabled:enabled];
			
			UIBarButtonItem *button = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"egopv_minimize_fullscreen_button.png"] style:UIBarButtonItemStyleBordered target:self action:@selector(toggleFullScreen:)];
			controller.navigationItem.rightBarButtonItem = button;
			[button release];
			
		}
		
	}
	
}





#pragma mark -
#pragma mark Photo View Methods

- (void)photoViewDidFinishLoading:(NSNotification*)notification{
	if (notification == nil) return;
	
	if ([[[notification object] objectForKey:@"photo"] isEqual:[self.photoSource photoAtIndex:[self centerPhotoIndex]]]) {
		if ([[[notification object] objectForKey:@"failed"] boolValue]) {
			if (_barsHidden) {
				//  image failed loading
				[self setBarsHidden:NO animated:YES];
			}
		} 
		[self setViewState];
	}
}

- (NSInteger)centerPhotoIndex{
	
	CGFloat pageWidth = self.scrollView.frame.size.width;
	return floor((self.scrollView.contentOffset.x - pageWidth / 2) / pageWidth) + 1;
	
}

- (void)moveForward:(id)sender{
	[self moveToPhotoAtIndex:[self centerPhotoIndex]+1 animated:NO];	
}

- (void)moveBack:(id)sender{
	[self moveToPhotoAtIndex:[self centerPhotoIndex]-1 animated:NO];
}

- (void)setViewState {	
	
	if (_leftButton) {
		_leftButton.enabled = !(_pageIndex-1 < 0);
	}
	
	if (_rightButton) {
		_rightButton.enabled = !(_pageIndex+1 >= [self.photoSource numberOfPhotos]);
	}
	
	if (_actionButton) {
		EGOPhotoImageView *imageView = [_photoViews objectAtIndex:[self centerPhotoIndex]];
		if ((NSNull*)imageView != [NSNull null]) {
			
			_actionButton.enabled = ![imageView isLoading];
			
		} else {
			
			_actionButton.enabled = NO;
		}
	}
	
	if ([self.photoSource numberOfPhotos] > 1) {
		self.title = [NSString stringWithFormat:@"%i of %i", _pageIndex+1, [self.photoSource numberOfPhotos]];
	} else {
		self.title = @"";
	}
	
	if (_captionView) {
		[_captionView setCaptionText:[[self.photoSource photoAtIndex:_pageIndex] caption] hidden:NO];
	}
	
#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
			
	if([self respondsToSelector:@selector(setContentSizeForViewInPopover:)] && [self.photoSource numberOfPhotos] == 1) {
		
		EGOPhotoImageView *imageView = [_photoViews objectAtIndex:[self centerPhotoIndex]];
		if ((NSNull*)imageView != [NSNull null]) {
			self.contentSizeForViewInPopover = [imageView sizeForPopover];
		}
		
	}
	
#endif
	
}

- (void)moveToPhotoAtIndex:(NSInteger)index animated:(BOOL)animated {
	NSAssert(index < [self.photoSource numberOfPhotos] && index >= 0, @"Photo index passed out of bounds");
	
	_pageIndex = index;
	[self setViewState];

	[self enqueuePhotoViewAtIndex:index];
	
	[self loadScrollViewWithPage:index-1];
	[self loadScrollViewWithPage:index];
	[self loadScrollViewWithPage:index+1];
	
	
	[self.scrollView scrollRectToVisible:((EGOPhotoImageView*)[self.photoViews objectAtIndex:index]).frame animated:animated];
	
	if ([[self.photoSource photoAtIndex:_pageIndex] didFail]) {
		[self setBarsHidden:NO animated:YES];
	}
	
	//  reset any zoomed side views
	if (index + 1 < [self.photoSource numberOfPhotos] && (NSNull*)[self.photoViews objectAtIndex:index+1] != [NSNull null]) {
		[((EGOPhotoImageView*)[self.photoViews objectAtIndex:index+1]) killScrollViewZoom];
	} 
	if (index - 1 >= 0 && (NSNull*)[self.photoViews objectAtIndex:index-1] != [NSNull null]) {
		[((EGOPhotoImageView*)[self.photoViews objectAtIndex:index-1]) killScrollViewZoom];
	} 	
	
}

- (void)layoutScrollViewSubviews{
	
	NSInteger _index = [self currentPhotoIndex];
	
	for (NSInteger page = _index -1; page < _index+3; page++) {
		
		if (page >= 0 && page < [self.photoSource numberOfPhotos]){
			
			CGFloat originX = self.scrollView.bounds.size.width * page;
			
			if (page < _index) {
				originX -= EGOPV_IMAGE_GAP;
			} 
			if (page > _index) {
				originX += EGOPV_IMAGE_GAP;
			}
			
			if ([self.photoViews objectAtIndex:page] == [NSNull null] || !((UIView*)[self.photoViews objectAtIndex:page]).superview){
				[self loadScrollViewWithPage:page];
			}
			
			EGOPhotoImageView *_photoView = (EGOPhotoImageView*)[self.photoViews objectAtIndex:page];
			CGRect newframe = CGRectMake(originX, 0.0f, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height);
			
			if (!CGRectEqualToRect(_photoView.frame, newframe)) {	
				
				[UIView beginAnimations:nil context:NULL];
				[UIView setAnimationDuration:0.1];
				_photoView.frame = newframe;
				[UIView commitAnimations];
			
			}
			
		}
	}
	
}

- (void)setupScrollViewContentSize{
	
	CGFloat toolbarSize = _popover ? 0.0f : self.navigationController.toolbar.frame.size.height;	
	
	CGSize contentSize = self.view.bounds.size;
	contentSize.width = (contentSize.width * [self.photoSource numberOfPhotos]);
	
	if (!CGSizeEqualToSize(contentSize, self.scrollView.contentSize)) {
		self.scrollView.contentSize = contentSize;
	}
	
	_captionView.frame = CGRectMake(0.0f, self.view.bounds.size.height - (toolbarSize + 40.0f), self.view.bounds.size.width, 40.0f);

}

- (void)enqueuePhotoViewAtIndex:(NSInteger)theIndex{
	
	NSInteger count = 0;
	for (EGOPhotoImageView *view in self.photoViews){
		if ([view isKindOfClass:[EGOPhotoImageView class]]) {
			if (count > theIndex+1 || count < theIndex-1) {
				[view prepareForReusue];
				[view removeFromSuperview];
			} else {
				view.tag = 0;
			}
			
		} 
		count++;
	}	
	
}

- (EGOPhotoImageView*)dequeuePhotoView{
	
	NSInteger count = 0;
	for (EGOPhotoImageView *view in self.photoViews){
		if ([view isKindOfClass:[EGOPhotoImageView class]]) {
			if (view.superview == nil) {
				view.tag = count;
				return view;
			}
		}
		count ++;
	}	
	return nil;
	
}

- (void)loadScrollViewWithPage:(NSInteger)page {
	
    if (page < 0) return;
    if (page >= [self.photoSource numberOfPhotos]) return;
	
	EGOPhotoImageView * photoView = [self.photoViews objectAtIndex:page];
	if ((NSNull*)photoView == [NSNull null]) {
		
		photoView = [self dequeuePhotoView];
		if (photoView != nil) {
			[self.photoViews exchangeObjectAtIndex:photoView.tag withObjectAtIndex:page];
			photoView = [self.photoViews objectAtIndex:page];
		}
		
	}
	
	if (photoView == nil || (NSNull*)photoView == [NSNull null]) {
		
		photoView = [[EGOPhotoImageView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, self.scrollView.bounds.size.width, self.scrollView.bounds.size.height)];
		[self.photoViews replaceObjectAtIndex:page withObject:photoView];
		[photoView release];
		
	} 
	[photoView setPhoto:[self.photoSource photoAtIndex:page] SmallPhoto:[self.smallphotoSource photoAtIndex:page]];
	
    if (photoView.superview == nil) {
		[self.scrollView addSubview:photoView];
	}
	
	CGRect frame = self.scrollView.frame;
	NSInteger centerPageIndex = _pageIndex;
	CGFloat xOrigin = (frame.size.width * page);
	if (page > centerPageIndex) {
		xOrigin = (frame.size.width * page) + EGOPV_IMAGE_GAP;
	} else if (page < centerPageIndex) {
		xOrigin = (frame.size.width * page) - EGOPV_IMAGE_GAP;
	}
	
	frame.origin.x = xOrigin;
	frame.origin.y = 0;
	photoView.frame = frame;
}


#pragma mark -
#pragma mark UIScrollView Delegate Methods


- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
	
	NSInteger _index = [self centerPhotoIndex];
	if (_index >= [self.photoSource numberOfPhotos] || _index < 0) {
		return;
	}
	
	if (_pageIndex != _index && !_rotating) {

		[self setBarsHidden:NO animated:YES];
		_pageIndex = _index;
		[self setViewState];
		
		if (![scrollView isTracking]) {
			[self layoutScrollViewSubviews];
		}
	}
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    NSLog(@"_pageIndex =%d",_pageIndex);
	NSInteger _index = [self centerPhotoIndex];
    NSLog(@"_index =%d",_index);
    NSLog(@"totall =%d",[self.photoSource numberOfPhotos]);
	if (_index >= [self.photoSource numberOfPhotos] || _index < 0) {
        NSLog(@"over");
		return;
	}
	
	[self moveToPhotoAtIndex:_index animated:YES];
    
    if (_barsHidden) {
        NSDictionary* tShowDic = [m_AssignISVC.m_ImagesDataArr objectAtIndex:self.currentPhotoIndex];
        NSString* tTitlePath = [tShowDic objectForKey:@"title"];
        NSString* tContentPath = [tShowDic objectForKey:@"digest"];
        if (![tTitlePath isEqualToString:@""] || ![tContentPath isEqualToString:@""]) {
            
            p_TipTitleLabel.frame = CGRectMake(48, 152+240, 484, 32);
            p_TipContentLabel.frame = CGRectMake(48,192+240, 484, 214);
            p_LabelButtonTip.frame = CGRectMake(82, 452+240, 52, 26);
            p_SeeSmallPageButton.frame =CGRectMake(46, 452+240, 25, 25);
            
            p_SeeForPages.frame = CGRectMake(30, 440+240, 520, 48);
            p_TipWordsView.frame = CGRectMake(30, 140+240, 520, 280);
            p_ContextController.frame =CGRectMake(30, 482+240, 520, 0);
            
            p_TipWordsView.frame = CGRectMake(30, 380, 520, 280);
            p_TipWordsView.alpha =0.6f;
            p_TipTitleLabel.frame = CGRectMake(18+30, 380+12, 484, 32);
            p_TipTitleLabel.alpha =1.0f;
            p_TipTitleLabel.text =tTitlePath;
            p_TipContentLabel.frame = CGRectMake(18+30,380+52, 484, 214);
            p_TipContentLabel.alpha =1.0f;
            p_TipContentLabel.text = tContentPath;
        }
    }
    
    if (m_IsMagezin && m_PageShowIndex == _index) {
        MainViewController* tMainView = [((UINavigationController*)((AppDelegate*)[UIApplication sharedApplication].delegate).window.rootViewController).viewControllers objectAtIndex:0];

        if (m_PageShowIndex == 0 && m_NowIndex-1 >= 0) {
            //左取
            NSLog(@"123");
            NSString* tMageIndexList = [tMainView.m_MageFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"mage%d.plist",m_NowIndex-1]];
            NSFileManager* tDefault = [NSFileManager defaultManager];
            if ([tDefault fileExistsAtPath:tMageIndexList]) {
                [tMainView relashEGOView:m_NowIndex-1 Page:0];
            }else{
                UIView* tLoadNextView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                [tLoadNextView setBackgroundColor:[UIColor blackColor]];
                tLoadNextView.alpha = 0.5f;
                tLoadNextView.tag =0x66;
                UIActivityIndicatorView* tActLoad = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(ScreenWidth/2-15, ScreenHeight/2-15, 30, 30)];
                [tActLoad startAnimating];
                [tLoadNextView addSubview:tActLoad];
                [tActLoad release];
                [self.view addSubview:tLoadNextView];
                [tLoadNextView release];
                
                NSString* tTidName = [(NSDictionary*)[m_SrcData objectAtIndex:m_NowIndex-1] objectForKey:@"tid"];
                NSString* tRequestPath = [NSString stringWithFormat:@"http://www.unitrue.com.cn:8088/ClientWebPage/CNewsList.aspx?tid=%@&begin=1&end=20",tTidName];
                NSLog(@"tRequestPath =%@",tRequestPath);
                ASIHTTPRequest* tLeftImgsListRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tRequestPath]];
                tLeftImgsListRequest.p_Tag = m_NowIndex-1;
                [tLeftImgsListRequest setDelegate:self];
                [tLeftImgsListRequest setDidFailSelector:@selector(requestMageImgs:)];
                [tLeftImgsListRequest setDidFinishSelector:@selector(requestMageImgsFinish:)];
                [tLeftImgsListRequest startAsynchronous];
            }

        }else if(m_PageShowIndex!=0 &&  m_NowIndex+1 < [m_SrcData count]){
            //右取
            NSLog(@"321");
            NSString* tMageIndexList = [tMainView.m_MageFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"mage%d.plist",m_NowIndex+1]];
            NSFileManager* tDefault = [NSFileManager defaultManager];
            if ([tDefault fileExistsAtPath:tMageIndexList]) {
                [tMainView relashEGOView:m_NowIndex+1 Page:0];
            }else{
                UIView* tLoadNextView =[[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight)];
                [tLoadNextView setBackgroundColor:[UIColor blackColor]];
                tLoadNextView.alpha = 0.5f;
                tLoadNextView.tag =0x66;
                UIActivityIndicatorView* tActLoad = [[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(ScreenWidth/2-15, ScreenHeight/2-15, 30, 30)];
                [tActLoad startAnimating];
                [tLoadNextView addSubview:tActLoad];
                [tActLoad release];
                [self.view addSubview:tLoadNextView];
                [tLoadNextView release];
                
                NSString* tTidName = [(NSDictionary*)[m_SrcData objectAtIndex:m_NowIndex+1] objectForKey:@"tid"];
                
                NSString* tRequestPath = [NSString stringWithFormat:@"http://www.unitrue.com.cn:8088/ClientWebPage/CNewsList.aspx?tid=%@&begin=1&end=20",tTidName];
                NSLog(@"tRequestPath =%@",tRequestPath);
                ASIHTTPRequest* tLeftImgsListRequest = [ASIHTTPRequest requestWithURL:[NSURL URLWithString:tRequestPath]];
                tLeftImgsListRequest.p_Tag = m_NowIndex+1;
                [tLeftImgsListRequest setDelegate:self];
                [tLeftImgsListRequest setDidFailSelector:@selector(requestMageImgs:)];
                [tLeftImgsListRequest setDidFinishSelector:@selector(requestMageImgsFinish:)];
                [tLeftImgsListRequest startAsynchronous];
            }
        }

    }
    m_PageShowIndex = _index;
}

//杂志数据获得失败 
-(void) requestMageImgs:(ASIHTTPRequest*) request{
    NSLog(@"杂志数据获得失败");
    [[self.view viewWithTag:0x66] removeFromSuperview];
    UIAlertView* tAlert = [[UIAlertView alloc] initWithTitle:@"提示" message:@"获得后续数据失败" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [tAlert show];
    [tAlert release];
}
//杂志数据得成功
-(void) requestMageImgsFinish:(ASIHTTPRequest*) request{
    NSString* httpdata = [request responseString];
	NSLog(@"http context = %@",httpdata);
	NSData *jsonData = [httpdata dataUsingEncoding:NSUTF32BigEndianStringEncoding];
	NSError *error = nil;
	NSDictionary* tDataDic = [[CJSONDeserializer deserializer] deserializeAsDictionary:jsonData error:&error] ;
    
    NSMutableArray* tTempArr = nil;
	if (error == nil) {
        NSLog(@"tag =%d",request.p_Tag);
        NSString* tTidName = [(NSDictionary*)[m_SrcData objectAtIndex:request.p_Tag] objectForKey:@"tid"];
        NSArray* tDataImgsArr = [tDataDic objectForKey:tTidName];
        tTempArr = [NSMutableArray arrayWithArray:tDataImgsArr];
        
        MainViewController* tMainView = [((UINavigationController*)((AppDelegate*)[UIApplication sharedApplication].delegate).window.rootViewController).viewControllers objectAtIndex:0];
        
        NSString* tMageIndexList = [tMainView.m_MageFolderPath stringByAppendingPathComponent:[NSString stringWithFormat:@"mage%d.plist",request.p_Tag]];
        [tTempArr writeToFile:tMageIndexList atomically:YES];
        
        [tMainView relashEGOView:request.p_Tag Page:0];
    }
    [[self.view viewWithTag:0x66] removeFromSuperview];
}

- (void)scrollViewWillBeginDecelerating:(UIScrollView *)scrollView{
	[self layoutScrollViewSubviews];
}


#pragma mark -
#pragma mark Actions

- (void)doneSavingImage{
	NSLog(@"done saving image");
}

- (void)savePhoto{
	
	UIImageWriteToSavedPhotosAlbum(((EGOPhotoImageView*)[self.photoViews objectAtIndex:_pageIndex]).imageView.image, nil, nil, nil);
	
}

- (void)copyPhoto{
	
	[[UIPasteboard generalPasteboard] setData:UIImagePNGRepresentation(((EGOPhotoImageView*)[self.photoViews objectAtIndex:_pageIndex]).imageView.image) forPasteboardType:@"public.png"];
	
}

- (void)emailPhoto{
	
//	MFMailComposeViewController *mailViewController = [[MFMailComposeViewController alloc] init];
//	[mailViewController setSubject:@"Shared Photo"];
//	[mailViewController addAttachmentData:[NSData dataWithData:UIImagePNGRepresentation(((EGOPhotoImageView*)[self.photoViews objectAtIndex:_pageIndex]).imageView.image)] mimeType:@"png" fileName:@"Photo.png"];
//	mailViewController.mailComposeDelegate = self;
//	
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
//	if (UI_USER_INTERFACE_IDIOM()==UIUserInterfaceIdiomPad) {
//		mailViewController.modalPresentationStyle = UIModalPresentationPageSheet;
//	}
//#endif
//	
//	[self presentModalViewController:mailViewController animated:YES];
//	[mailViewController release];
	
}

//- (void)mailComposeController:(MFMailComposeViewController*)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError*)error{
//	
//	[self dismissModalViewControllerAnimated:YES];
//	
//	NSString *mailError = nil;
//	
//	switch (result) {
//		case MFMailComposeResultSent: ; break;
//		case MFMailComposeResultFailed: mailError = @"Failed sending media, please try again...";
//			break;
//		default:
//			break;
//	}
//	
//	if (mailError != nil) {
//		UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"" message:mailError delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//		[alert show];
//		[alert release];
//	}
//	
//}


#pragma mark -
#pragma mark UIActionSheet Methods

//- (void)actionButtonHit:(id)sender{
//	
//	UIActionSheet *actionSheet;
//	
//	if ([MFMailComposeViewController canSendMail]) {
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
//		if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && !_popover) {
//			actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", @"Email", nil];
//		} else {
//			actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", @"Email", nil];
//		}
//#else
//		actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", @"Email", nil];
//#endif
//		
//	} else {
//		
//#if __IPHONE_OS_VERSION_MAX_ALLOWED >= 30200
//		if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad && !_popover) {
//			actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:nil destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", nil];
//		} else {
//			actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", nil];
//		}
//#else
//		actionSheet = [[UIActionSheet alloc] initWithTitle:@"" delegate:self cancelButtonTitle:@"Cancel" destructiveButtonTitle:nil otherButtonTitles:@"Save", @"Copy", nil];
//#endif
//		
//	}
//	
//	actionSheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
//	actionSheet.delegate = self;
//	
//	[actionSheet showInView:self.view];
//	[self setBarsHidden:YES animated:YES];
//	
//	[actionSheet release];
//	
//}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex{
	
	[self setBarsHidden:NO animated:YES];
	
	if (buttonIndex == actionSheet.cancelButtonIndex) {
		return;
	} else if (buttonIndex == actionSheet.firstOtherButtonIndex) {
		[self savePhoto];
	} else if (buttonIndex == actionSheet.firstOtherButtonIndex + 1) {
		[self copyPhoto];	
	} else if (buttonIndex == actionSheet.firstOtherButtonIndex + 2) {
		[self emailPhoto];	
	}
}


#pragma mark -
#pragma mark Memory

- (void)didReceiveMemoryWarning{
	[super didReceiveMemoryWarning];
}

- (void)viewDidUnload{
	
	self.photoViews=nil;
	self.scrollView=nil;
	_captionView=nil;
	
}

- (void)dealloc {
    [p_SendMailView release];
    [p_ContextController release];
    [p_LabelButtonTip release];
    [p_SeeSmallPageButton release];
    [p_TipTitleLabel release];
    [p_TipContentLabel release];
    [p_TipWordsView release];
    [p_SeeForPages release];
	[p_PopShowWord release];
	[[NSNotificationCenter defaultCenter] removeObserver:self];
	
	_captionView=nil;
	[_photoViews release], _photoViews=nil;
	[_photoSource release], _photoSource=nil;
	[_scrollView release], _scrollView=nil;
	[_oldToolBarTintColor release], _oldToolBarTintColor = nil;
	[_oldNavBarTintColor release], _oldNavBarTintColor = nil;
	[UIShareLittle release];
    [super dealloc];
}


@end